package com.example.JavaWebApi.core.apifilters;

import com.example.JavaWebApi.core.apifilters.components.RequestWrapper;
import com.example.JavaWebApi.core.apifilters.components.ResponseWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: cnu-api-java
 * @description:
 * @author: 杨泽
 * @create: 2023-07-26 13:34
 */
@Component
@Slf4j
@Order(1)
public class BodyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String contentType = servletRequest.getContentType();
        String method = "multipart/form-data";

        if (contentType != null && contentType.contains(method)) {
            // 将转化后的 request 放入过滤链中
            request = new StandardServletMultipartResolver().resolveMultipart(request);
        }
        ServletRequest requestWrapper = new RequestWrapper(request);
        ServletResponse responseWrapper = new ResponseWrapper((HttpServletResponse) servletResponse);
        filterChain.doFilter(requestWrapper, responseWrapper);
    }
}